<?php include('scripts.php');

?>
<script type="text/javascript">
var datagridOpenTransaction = null;
var datagridBuyingHistory = null;
var datagridSellingHistory = null;
var datagridWaitingList = null;
$(function() {
    $("#tradingForm").validate({
        messages : {

        },
        rules : {

        },
        submitHandler: function(form) {
            waiting();
            var buyAmount = $('#txtBuyAmount').autoNumericGet();
            var ecashBalance = $('#txtEcash').val();

            if (parseFloat(ecashBalance) < (parseFloat(buyAmount))) {
                alert("<?php echo __("In-sufficient e-Cash")?>");
                return false;
            }
            if (parseFloat(buyAmount) == 0) {
                alert("<?php echo __("Buy amount must be greater than 0")?>");
                return false;
            }

            $("#txtBuyAmount").val(buyAmount);
            form.submit();
        }
    });

    $("#btnBuy").button({
        icons: {
            primary: "ui-icon-cart"
        }
    });
    $('#txtBuyAmount').autoNumeric({
        mDec: 2
    });
    $('#dgBuyQuantity').autoNumeric({
        mDec: 0
    });

    $("#goldTradingTabs").tabs().find(".ui-tabs-nav");

    /*datagridOpenTransaction = $("#datagridOpenTransaction").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
            reassignDatagridOpenTransactionEventAttr();
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/eshare/openTransactionListing",
        "sPaginationType": "full_numbers",
        //"aaSorting": [[5,'desc']],
        "aoColumns": [
                      { "sName" : "eshare_id", "bVisible" : false,  "bSortable": true},
                      { "sName" : "eshare_id", "bSortable": true},
                      { "sName" : "buy_price",  "bSortable": false},
                      { "sName" : "credit",  "bSortable": false},
                      { "sName" : "profit", "bVisible" : true,  "bSortable": false},
                      { "sName" : "valid_sell_date",  "bSortable": true},
                      { "sName" : "valid_sell_date",  "bSortable": true,
                        "fnRender": function ( oObj ) {
                            <?php
                                if($validToSellShare == true){
                            ?>
                                if (oObj.aData[6]) {
                                    $("#datagridOpenTransaction").data("openTransaction_" + oObj.aData[0], oObj.aData);
                                    return "<a id='sellLink' href='#' style='color:red'><?php echo __('Sell', null, "goldTrading") ?></a>";
                                } else {
                                    return "";
                                }
                            <?php
                                } else {
                                    echo 'return ""';
                                }
                            ?>
                        }
                      }
        ]
    });*/

    datagridWaitingList = $("#datagridWaitingList").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
            reassignDatagridBuyEventAttr();
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/eshare/sellingWaitingListing",
        "sPaginationType": "full_numbers",
        "aaSorting": [[1,'desc']],
        "aoColumns": [
          { "sName" : "sell.sell_id", "bVisible" : false,  "bSortable": true},
          { "sName" : "sell.created_on",  "bSortable": true},
          { "sName" : "dist.distributor_code", "bSortable": true},
          { "sName" : "sell.price",  "bSortable": true},
          { "sName" : "sell.qty",  "bSortable": true},
          { "sName" : "sell.qty",  "bSortable": true,
            "fnRender": function ( oObj ) {
                    $("#dgBuyConfirmation").data("data_" + oObj.aData[0], {
                        sell_id : oObj.aData[0]
                        , created_on : oObj.aData[2]
                        , distributor_name : oObj.aData[2]
                        , price : oObj.aData[3]
                        , qty : oObj.aData[4]
                  });
                return "<a id='buyLink' href='#' style='color:red'><?php echo __('Buy', null, "goldTrading") ?></a>";
            }
          }
        ]
    });

    datagridBuyingHistory = $("#datagridBuyingHistory").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/eshare/buyingHistoryListing",
        "sPaginationType": "full_numbers",
        "aaSorting": [[1,'desc']],
        "aoColumns": [
                      { "sName" : "eshare_id", "bVisible" : false,  "bSortable": true},
                      { "sName" : "created_on",  "bSortable": true},
                      { "sName" : "eshare_id", "bSortable": true},
                      { "sName" : "credit",  "bSortable": true},
                      { "sName" : "buy_price",  "bSortable": true}

        ]
    });

    /*datagridSellingHistory = $("#datagridSellingHistory").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/eshare/sellingHistoryListing",
        "sPaginationType": "full_numbers",
        "aaSorting": [[6,'desc']],
        "aoColumns": [
                      { "sName" : "eshare_id", "bVisible" : false,  "bSortable": true},
                      { "sName" : "eshare_id", "bSortable": true},
                      { "sName" : "debit",  "bSortable": true},
                      { "sName" : "sell_price",  "bSortable": true},
                      { "sName" : "profit",  "bSortable": true},
                      { "sName" : "sell_date",  "bSortable": true}
        ]
    });*/

    $("#dgSellConfirmation").dialog("destroy");
    $("#dgSellConfirmation").dialog({
        autoOpen : false,
        modal : true,
        resizable : false,
        hide: 'clip',
        show: 'slide',
        height: 160,
        buttons: {
            "<?php echo __('Confirm') ?>": function() {
                waiting();
                $("#sellShareForm").submit();
                $(this).dialog('close');
            },
            "<?php echo __('Cancel') ?>": function() {
                $(this).dialog('close');
            }
        }
    });

    $("#dgBuyConfirmation").dialog("destroy");
    $("#dgBuyConfirmation").dialog({
        autoOpen : false,
        modal : true,
        resizable : false,
        hide: 'clip',
        show: 'slide',
        width: 550,
        height: 200,
        buttons: {
            "<?php echo __('Confirm') ?>": function() {
                waiting();
                var buyQuantity = $('#dgBuyQuantity').autoNumericGet();
                $("#buyId").val($("#dgBuyId").val());
                $("#buyQuantity").val(buyQuantity);
                $("#buyShareForm").submit();
                $(this).dialog('close');
            },
            "<?php echo __('Cancel') ?>": function() {
                $(this).dialog('close');
            }
        }
    });

    $("#dgBuyQuantity").keyup(function(){
        var buyQuantity = $('#dgBuyQuantity').autoNumericGet();
        var amount = parseFloat(buyQuantity) * parseFloat($("#dgBuyPrice").val());

        $("#dgTotalAmount").val(amount);
    });

    setInterval(function() {
        datagridWaitingList.fnDraw();
    }, 10000);
})

function reassignDatagridBuyEventAttr(){
	$("a[id=buyLink]").click(function(event){
		event.preventDefault();

		var id = $(event.target).parent().parent().attr("id");
        var data = $("#dgBuyConfirmation").data("data_" + id);
        $("#dgBuyId").val(id);
        $("#dgBuyPrice").val(data.price);
        $("#dgBuyQuantity").val(data.qty);
        $("#dgBuyMaxQty").val(data.qty);
        $("#dgTotalAmount").val(0);
        $("#dgBuyConfirmation").dialog("open");
        $("#dgBuyQuantity").trigger("keyup");
	});
}
function reassignDatagridOpenTransactionEventAttr(){
	$("a[id=sellLink]").click(function(event){
		event.preventDefault();

		var id = $(event.target).parent().parent().attr("id");
        $("#shareId").val(id);
        $("#dgSellConfirmation").dialog("open");
	});
}
</script>

<div style="padding: 10px; top: 30px; width: 98%">
    <table>
        <?php if ($sf_flash->has('errorMsg')): ?>
        <tr>
            <td>
                <div class="ui-widget">
                    <div style="margin-top: 20px; padding: 0 .7em;" class="ui-state-error ui-corner-all">
                        <p><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-alert"></span>
                        <strong><?php echo $sf_flash->get('errorMsg') ?></strong></p>
                    </div>
                </div>
            </td>
        </tr>
        <?php endif; ?>
        <?php if ($sf_flash->has('successMsg')): ?>
        <tr>
            <td>
                <div class="ui-widget">
                    <div style="margin-top: 20px; padding: 0 .7em;" class="ui-state-highlight ui-corner-all">
                        <p><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-info"></span>
                        <strong><?php echo $sf_flash->get('successMsg') ?></strong></p>
                    </div>
                </div>
            </td>
        </tr>
        <?php endif; ?>
        <tr>
            <td>
                <div class="portlet">
                    <div class="portlet-header"><?php echo __('Cash Flow Point Chart') ?></div>
                    <div class="portlet-content">
                        <div id="container" style="min-width: 400px; width:600px;height:300px; margin: 0 auto"></div>
                    </div>
                </div>
            </td>
            <td valign="top">
                <table width="98%" height="340" cellspacing="0" cellpadding="1" border="0" align="center" id="tableInfo">
                    <tbody>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Daily Shares Trading Volume (Buy)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($eshareTradingDto->getDailySharesTradingVolumeBuy(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('(Sell)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($eshareTradingDto->getDailySharesTradingVolumeSell(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Monthly Shares Trading Volume (Buy)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($eshareTradingDto->getMonthlySharesTradingVolumeBuy(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('(Sell)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($eshareTradingDto->getMonthlySharesTradingVolumeSell(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Next Increment', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($eshareTradingDto->getNextIncrement(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Paper e-Share Quantity', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span id="spanPaperGoldQuantity"><?php echo number_format($eshareTradingDto->getPaperEshareQuantity(),0)?></span>
                            <span id="MyGoldAccount1_Label3"> <?php echo __('unit', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Average Price (Buy)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B">
                                <span id="MyGoldAccount1_Label5">$</span><span id="spanAveragePriceBuy"><?php echo number_format($eshareTradingDto->getAveragePriceBuy(),2)?></span>
                                <span id="MyGoldAccount1_Label4">/<?php echo __('unit', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Total Share Value', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B">
                                <span>$</span><span><?php echo number_format($eshareTradingDto->getPaperEshareQuantity() * $eshareTradingDto->getEsharePrice(),2)?></span>
                            </font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('e-Cash', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B">
                                <span id="MyGoldAccount1_Label2">$</span>
                                <span id="spanEcash"><?php echo number_format($eshareTradingDto->getEcash(),2)?></span>
                                <input type="hidden" id="txtEcash" value="<?php echo $eshareTradingDto->getEcash()?>">
                            </font>
                        </td>
                    </tr>

                    <tr>
                        <td valign="baseline" align="right">
                            <strong><?php echo __('We sell', null, "goldTrading") ?>:</strong>
                        </td>
                        <td valign="baseline" align="left">
                            <form action="/eshare/buyShare" id="tradingForm" method="post">
                                <span style="color:#61210B;" id="Label4">$</span>
                                <span style="color:#61210B;" id="spanGoldSell"><?php echo $eshareTradingDto->getEsharePrice()?></span>
                                <span style="color:#61210B;" id="Labelusdbuy">/<?php echo __('unit', null, "goldTrading") ?></span>&nbsp;
                                <br>
                                <input type="text" style="width:80px; margin-top: 5px; margin-bottom: 5px" id="txtBuyAmount" name="txtBuyAmount">
                                <span id="Labelgram"><strong><?php echo __('USD', null, "goldTrading") ?></strong></span>&nbsp;&nbsp;

                                    <?php
                                    if($validToBuyShare == true){
                                    ?>
                                        <button id="btnBuy"><?php echo __('Buy', null, "goldTrading") ?></button>
                                    <?php
                                        }
                                    ?>
                            </form>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </table>
</div>
<form action="/eshare/sellShare" id="sellShareForm" method="post">
    <input type="hidden" name="shareId" id="shareId" value="">
</form>
<form action="/eshare/buyShareFromWaitingList" id="buyShareForm" method="post">
    <input type="hidden" name="buyId" id="buyId" value="0">
    <input type="hidden" name="buyQuantity" id="buyQuantity" value="0">
</form>
<div id="goldTradingTabs">
    <ul>
        <!--<li><a href="#tabs-openTransactions"><?php /*echo __('Open Transactions', null, 'goldTrading') */?></a></li>-->
        <li><a href="#tabs-waitingList"><?php echo __('Waiting List', null, 'goldTrading') ?></a></li>
        <li><a href="#tabs-buyingHistory"><?php echo __('Buying History', null, 'goldTrading') ?></a></li>
        <!--<li><a href="#tabs-sellingHistory"><?php /*echo __('Selling History', null, 'goldTrading') */?></a></li>-->
    </ul>
    <!--<div id="tabs-openTransactions">
        <table class="display" id="datagridOpenTransaction" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php /*echo __('Transaction ID', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Price($/unit)', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Quantity(unit)', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Unrealized Profit/Loss($)', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Valid Sell Date', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Action', null, 'goldTrading') */?></th>
            </tr>
            </thead>
        </table>
    </div>-->
    <!--################    Waiting List  ###################-->
    <div id="tabs-waitingList">
        <table class="display" id="datagridWaitingList" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php echo __('Time', null, 'goldTrading') ?></th>
                <th><?php echo __('Shareholder ID', null, 'goldTrading') ?></th>
                <th><?php echo __('Price', null, 'goldTrading') ?></th>
                <th><?php echo __('Qty', null, 'goldTrading') ?></th>
                <th><?php echo __('Action', null, 'goldTrading') ?></th>
            </tr>
            </thead>
        </table>
    </div>
    <!--################    Buying History  ###################-->
    <div id="tabs-buyingHistory">
        <table class="display" id="datagridBuyingHistory" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php echo __('Buy Date', null, 'goldTrading') ?></th>
                <th><?php echo __('Transaction ID', null, 'goldTrading') ?></th>
                <th><?php echo __('Quantity(unit)', null, 'goldTrading') ?></th>
                <th><?php echo __('Buy Price($/unit)', null, 'goldTrading') ?></th>
            </tr>
            </thead>
        </table>
    </div>
    <!--##############  Selling History  #####################-->
    <!--<div id="tabs-sellingHistory">
        <table class="display" id="datagridSellingHistory" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php /*echo __('Transaction ID', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Quantity(unit)', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Sell Price($/unit)', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Realised Profit/Loss', null, 'goldTrading') */?></th>
                <th><?php /*echo __('Sell Date', null, 'goldTrading') */?></th>
            </tr>
            </thead>
        </table>
    </div>-->
</div>

<div id="dgSellConfirmation" title="<?php echo __('Sell e-Share', null, 'goldTrading') ?>" style="display:none;">
    <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span><?php echo __('Are you sure you want to sell CPS?', null, 'goldTrading') ?></p>
</div>

<div id="dgBuyConfirmation" title="<?php echo __('Order Entry', null, 'goldTrading') ?>" style="display:none;">
    <input type="hidden" id="dgBuyId">
    <input type="hidden" id="dgBuyMaxQty">
    <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span><?php echo __('Are you sure you want to buy CPS?', null, 'goldTrading') ?></p>
    <hr>
    <table cellpadding="3" cellspacing="3">
        <tr>
            <td><strong>Quantity:</strong></td>
            <td><input id="dgBuyQuantity" value="0" style="width: 60px"></td>
            <td>&nbsp;</td>
            <td><strong>Price:</strong></td>
            <td><input id="dgBuyPrice" value="" style="width: 60px" readonly="readonly"> USD</td>
            <td>&nbsp;</td>
            <td><strong>Amount:</strong></td>
            <td><input id="dgTotalAmount" value="" style="width: 60px" readonly="readonly"> USD</td>
        </tr>
    </table>
</div>

<?php
$str = "";
$lowestXaxis = 0;
$firstDate = null;
foreach ($eshareLogs as $eshareLog):
    if ($str != "") {
        $str = ",".$str;
    }
    $str = $eshareLog['share_value'].$str;

    if ($lowestXaxis == 0) {
        $lowestXaxis = $eshareLog['share_value'];
    } else if ($eshareLog['share_value'] < $lowestXaxis) {
        $lowestXaxis = $eshareLog['share_value'];
    }
    if ($firstDate == null) {
        $firstDate = $eshareLog['created_on'];
    }
endforeach;

$dateUtil = new DateUtil();
$firstDateAfterDeduct = $dateUtil->addDate($firstDate, -30, 0, 0);

$milisec = strtotime($firstDateAfterDeduct);

/*var_dump("===========".$firstDate);
var_dump("===========".$firstDateAfterDeduct);
var_dump("===========".date("Y", $milisec));
var_dump("===========".date("m", $milisec));
var_dump("===========".date("j", $milisec));*/

$modulusValue = $lowestXaxis % 10;
$lowestXaxis = $lowestXaxis - $modulusValue;
?>
<script type="text/javascript">
    $(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'line',
                spacingRight: 20
            },
            title: {
                text: 'Cash Flow Point Chart'
            },
            subtitle: {
            },
            xAxis: {
                type: 'datetime',
                maxZoom: 1 * 24 * 3600000, // fourteen days
                title: {
                    text: null
                }
            },
            yAxis: {
                title: {
                    text: 'e-share price'
                },
                min: 0,
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                shared: true
            },
            legend: {
                enabled: false
            },
            series: [{
                /*type: 'area',*/
                name: 'Date vs e-Share Price',
                pointInterval: 1 * 24 * 3600000,
                pointStart: Date.UTC(<?php echo date("Y", $milisec) ?>, <?php echo date("m", $milisec) -1 ?>, <?php echo date("j", $milisec) + 1 ?>),
                data: [
                    <?php echo $str; ?>
                ]
            }]
        });
    });
});
</script>
